package com.sen.common.security.jcaptcha;

import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import com.octo.captcha.service.CaptchaService;
import com.octo.captcha.service.CaptchaServiceException;

import com.sen.common.utils.spring.SpringUtils;
import com.sen.common.utils.web.ServletUtils;

/**
 * 集成JCaptcha图片验证码的Servlet.
 * 
 * 在web.xml中配置的参数包括：
 * <ol>
 * <li>captchaServiceId -- captchaService在Spring中的bean id,默认为"captchaService".
 * </ol>
 * 
 * @author sen
 */
// FIXME 还没有完成, 总是报java.io.IOException: Closed.
public class JCaptchaImageServlet extends HttpServlet {
	// web.xml中的参数名定义
	public static final String PARAM_CAPTCHA_SERVICE_ID = "captchaServiceId";

	// 默认值定义
	public static final String DEFAULT_CAPTCHA_SERVICE_ID = "captchaService";

	private static final long serialVersionUID = -1148619624772571057L;

	private static Logger log = Logger.getLogger(JCaptchaImageServlet.class);
	
	private static String captchaServiceId = DEFAULT_CAPTCHA_SERVICE_ID;

	private static CaptchaService captchaService;
	
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		initParameters(config);
		initCaptchaService(config);
	}

	/**
	 * 初始化web.xml中定义的servlet init-param.
	 */
	private void initParameters(final ServletConfig config) {
		if (StringUtils.isNotBlank(config
				.getInitParameter(PARAM_CAPTCHA_SERVICE_ID))) {
			captchaServiceId = config
					.getInitParameter(PARAM_CAPTCHA_SERVICE_ID);
		}
	}

	/**
	 * 从ApplicatonContext获取CaptchaService实例.
	 */
	private void initCaptchaService(final ServletConfig config) {
		captchaService = SpringUtils.getBean(config.getServletContext(),
				captchaServiceId, CaptchaService.class);
	}

	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		super.doGet(request, response);
		genernateCaptchaImage(request, response);
	}

	/**
	 * 生成验证码图片.
	 */
	private void genernateCaptchaImage(final HttpServletRequest request,
			final HttpServletResponse response) throws ServletException, IOException {

		ServletUtils.setDisableCacheHeader(response);
		response.setContentType("image/jpeg");

		try {
			String captchaId = request.getSession(true).getId();
			BufferedImage challenge = (BufferedImage) captchaService
					.getChallengeForID(captchaId, request.getLocale());
			ImageIO.write(challenge, "jpg", response.getOutputStream());
		} catch (CaptchaServiceException e) {
			log.error(e.getMessage(), e);
		}
	}

}
